package edu.umn.msse.farside.FourH.web;

import edu.umn.msse.farside.FourH.domain.Volunteer;
import edu.umn.msse.farside.FourH.exceptions.DuplicateVolunteerException;
import edu.umn.msse.farside.FourH.exceptions.InvalidEmailException;
import edu.umn.msse.farside.FourH.services.VolunteerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;

/**
 * Created by IntelliJ IDEA.
 * User: corcutt
 * Date: Mar 17, 2009
 * Time: 8:18:11 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/editVolunteer")
public class EditVolunteerController
{
    public VolunteerService volunteerService;

    @Autowired
    public void setVolunteerService(VolunteerService volunteerService)
    {
        this.volunteerService = volunteerService;
    }
  
    @RequestMapping(method = RequestMethod.GET)
    public String editVolunteerForm(Model model, HttpSession session)
    {
        Volunteer volunteer = (Volunteer)session.getAttribute("volunteer");
        model.addAttribute("volunteer", volunteer);
        return "editVolunteer";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String editVolunteer(@ModelAttribute(value="volunteer") Volunteer volunteer, BindingResult result, HttpSession session)
    {
        if (StringUtils.isBlank(volunteer.getEmail())) {
            result.rejectValue("email", "required", "Required");  // property resource
        }
        if (StringUtils.isBlank(volunteer.getPassword())) {
            result.rejectValue("password", "required", "Required");
        }

        if (!result.hasErrors()) {

            try
            {
                volunteerService.updateVolunteer(volunteer);
                session.setAttribute("volunteer", volunteer); // reset session with new volunteer values
            }
            catch (InvalidEmailException e)
            {
                result.rejectValue("email", "InvalidEmail", "Invalid Email format");  // property resource
            }
            catch (DuplicateVolunteerException e)
            {
                result.rejectValue("email", "DuplicateVolunteer", "Someone is register in the system with this email!");  // property resource                
            }
        }

        return result.hasErrors() ? "editVolunteer" : "redirect:futureEvents";
    }

}
